package hk.ust.cse.comp3111.studentSchedule;

import hk.ust.cse.comp3111.studentSchedule.ViewCalendar_week.MyListener;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

public class ViewCalendar_singleItem extends Fragment{
	
	GridView gv;
	ArrayAdapter<String> adapter;
	Button edit_single;
	Button delete_single;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.calendar_single_item, container, false);
        
        
        return rootView;
    }
	
	@Override
	public void onStart() {
		super.onStart();
		
		edit_single = (Button) this.getActivity().findViewById(R.id.edit_single);
		delete_single= (Button) this.getActivity().findViewById(R.id.delete_single);
		
		Bundle args = getArguments();
		long eventID = Long.parseLong(args.getString("eventID"));
		gv = (GridView) this.getView().findViewById(R.id.calendar_single_grid);
		
		String test = args.getString("eventID");
		String start=args.getString("start");
		String end = args.getString("end");
		//Toast.makeText(this.getActivity().getApplicationContext(), "eventID is "+test+start+end, Toast.LENGTH_LONG).show();
		
		
		Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
		
		ContentUris.appendId(eventsUriBuilder, Long.parseLong(start));
		ContentUris.appendId(eventsUriBuilder, Long.parseLong(end));
		Uri eventsUri = eventsUriBuilder.build();
		Cursor cur = null;  
		ArrayList<String> listItems=new ArrayList<String>();
		String[] columns = new String[] { "calendar_id", "title", "description", "event_id", "startDay", "startMinute" , "endMinute", "eventLocation"};
		
		String selection ="event_id = ? "; 
		   String[] argss = 
		         new String[]{test}; 
		
		cur = this.getActivity().getContentResolver().query(eventsUri, columns, selection, argss, CalendarContract.Instances.DTSTART + " ASC");
		
		//Toast.makeText(getActivity(),"cur is  "+cur.getCount(),Toast.LENGTH_SHORT).show();
		
		if (cur.moveToFirst()) {
			listItems.add(cur.getString(1));
			listItems.add(cur.getString(2));
			int[] day=fromJulian(Long.parseLong(cur.getString(4)));
			String[] time=timeCoversation(Long.parseLong(cur.getString(5)));
			String[] timeEnd=timeCoversation(Long.parseLong(cur.getString(6)));
			listItems.add(day[0]+"/"+day[1]+"/"+day[2]);
			listItems.add(time[0]+":"+time[1]+" - "+timeEnd[0]+":"+timeEnd[1]);
			
			if(cur.getString(7)!=null)
				listItems.add(cur.getString(7));
			
			
			
		}
		
		
		
		adapter=new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1,listItems);
		gv.setAdapter(adapter);
		listener_edit listener_edit = new listener_edit();
		listener_del listener_del = new listener_del();
		
		
		listener_edit.setValue(test);
		listener_del.setValue(test);
		
		listener_edit.setTime(start, end);
		listener_del.setTime(start, end);
		
		
		edit_single.setOnClickListener(listener_edit);
		
		delete_single.setOnClickListener(listener_del);
		
		
	}
	
	private int[] fromJulian(double injulian) {  
		   int jalpha,ja,jb,jc,jd,je,year,month,day;  
		   double HALFSECOND = 0.5;  
		   int JGREG= 15 + 31*(10+12*1582);  
		   
		   double julian = injulian + HALFSECOND / 86400.0;  
		   ja = (int) injulian;  
		   if (ja>= JGREG) {      
		     jalpha = (int) (((ja - 1867216) - 0.25) / 36524.25);  
		     ja = ja + 1 + jalpha - jalpha / 4;  
		   }  
		     
		   jb = ja + 1524;  
		   jc = (int) (6680.0 + ((jb - 2439870) - 122.1) / 365.25);  
		   jd = 365 * jc + jc / 4;  
		   je = (int) ((jb - jd) / 30.6001);  
		   day = jb - jd - (int) (30.6001 * je);  
		   month = je - 1;  
		   if (month > 12) month = month - 12;  
		   year = jc - 4715;  
		   if (month > 2) year--;  
		   if (year <= 0) year--;  
		     
		   return new int[] {year, month, day};  
		  }
	
	//convert minute to time
	private String[] timeCoversation(double time){
		String hr, minute;
		
		hr = Integer.toString((int) time/60);
		minute = Integer.toString((int) time%60);
		
		if(hr.length()==1) hr="0"+hr;
		if(minute.length()==1) minute="0"+minute;
	
		
		return new String[]{hr,minute};
		
	}
	
	private void push(String eventID,String start, String end) {
    	Bundle save=new Bundle();
		save.putString("eventID",eventID);
		save.putString("start", start);
		save.putString("end", end);
		Fragment fragment = new EditEvent();
		fragment.setArguments(save); 
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.frame_container, fragment).commit();
		
	}
	
	private void push_del(String eventID,String start, String end) {
    	Bundle save=new Bundle();
		save.putString("eventID",eventID);
		save.putString("start", start);
		save.putString("end", end);
		Fragment fragment = new ViewCalendar_singleItem();
		fragment.setArguments(save); 
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.frame_container, fragment).commit();
		
	}
	
	class listener_edit implements OnClickListener
	{ 
	    String nulls;
	    String eventID;
	    String start;
	    String end;

	    void setName(String newName)
	    {
	    	nulls = newName;
	    }

	    void setValue(String newValue)
	    {
	    	eventID = newValue;
	    }
	    
	    void setTime(String a, String b)
	    {
	        start =a;
	        end =b;
	    }
	    
	    
	    public void onClick(View v) 
	    {
	    	Activity activity = getActivity();
	        // Use the data for some unknown purpose
	    	//Toast.makeText(activity,"you clicked ID "+value,Toast.LENGTH_LONG).show();
	    	push(eventID,start,end);
	    	//Toast.makeText(activity,"you clicked ID "+eventID,Toast.LENGTH_LONG).show();
	    	//Toast.makeText(activity,"time "+start,Toast.LENGTH_LONG).show();
	    	//Toast.makeText(activity,"time "+end,Toast.LENGTH_LONG).show();
	    }


	}
	
	class listener_del extends listener_edit implements OnClickListener{
		public void onClick(View v) 
	    {
			long eventIDD=Long.parseLong(eventID);
			ContentValues values = new ContentValues();
			Uri deleteUri = null;
			deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventIDD);
			int rows = getActivity().getContentResolver().delete(deleteUri, null, null);
			Activity activity = getActivity();
			Toast.makeText(activity,"Event deleted",Toast.LENGTH_LONG).show();
			Fragment fragment = new ViewCalendar();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();
	    }
	}
	
	

}
